package com.promote.hotspot.server.netty.filter;

import com.promote.hotspot.server.hot.HotSpotQueue;
import com.promote.hotspot.server.hot.Producer;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.java.Log;
import org.apache.commons.collections.CollectionUtils;
import org.promote.hotspot.common.model.HotKeyModel;
import org.promote.hotspot.common.model.HotSpotMsg;
import org.promote.hotspot.common.model.MessageType;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;


/**
 * 热点数据处理
 *
 * @author enping.jep
 * @date 2023/11/16 11:22
 **/
@Component
@Order(3)
@Log
public class HotSpotFilter implements INettyMsgFilter {

    @Resource
    private Producer producer;

    @Resource
    private HotSpotQueue hotSpotCounter;


    @Override
    public boolean chain(HotSpotMsg message, ChannelHandlerContext ctx) {
        if (MessageType.REQUEST_NEW_KEY == message.getMessageType()) {
            log.info("HotSpotFilter receive message:" + message.toString());
            hotSpotCounter.addTotalCount();//总量累计
            publishMsg(message, ctx);//把消息给发到生产者
            return false;
        }
        return true;
    }

    /**
     * 生产者-消费者模型
     *
     * @param message 原始报文
     * @param ctx     ChannelHandlerContext
     */
    private void publishMsg(HotSpotMsg message, ChannelHandlerContext ctx) {
        List<HotKeyModel> list = message.getHotKeyModels();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (HotKeyModel model : list) {
            producer.push(model);
        }
    }
}